package com.ybb.production.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Date;

import com.yubb.common.core.redis.RedisCache;

/**
 * 工单号生成器
 *
 * @author dengjie
 * @version 1.0
 * @date 2023/9/18 10:17
 */
@Component
public class WorkOrderNumberGenerator {
    private static final String COUNTER_KEY = "work_order_counter";

    @Autowired
    public RedisCache redisCache;

    public String generateWorkOrderNumber() {
        RedisTemplate redisTemplate = redisCache.redisTemplate;
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取当天的起始时间戳（秒）
        long startOfDay = currentDate.atStartOfDay().toEpochSecond(ZoneOffset.UTC);

        ValueOperations<String, String> valueOperations = redisCache.redisTemplate.opsForValue();

        // 获取计数器键的过期时间
        Long expirationTime = redisTemplate.getExpire(COUNTER_KEY);

        // 如果过期时间小于等于0，表示需要重置计数器
        if (expirationTime <= 0) {
            // 重置计数器
            valueOperations.set(COUNTER_KEY, "1");
            // 设置计数器键的过期时间为当天剩余的秒数
            redisTemplate.expireAt(COUNTER_KEY, Date.from(Instant.ofEpochSecond(startOfDay + 86400))); // 86400 秒 = 1 天
        } else {
            // 使用 INCR 命令递增计数器
            Long counter = valueOperations.increment(COUNTER_KEY, 1);
        }

        // 生成工单号
        String datePrefix = currentDate.toString().replaceAll("-", "");
        String workOrderNumber = datePrefix + valueOperations.get(COUNTER_KEY);
        return workOrderNumber;
    }


}
